package com.novel.common.job;

import com.google.common.collect.ImmutableListMultimap;
import com.google.common.collect.Multimaps;
import com.novel.mapper.ChapterOrderMapper;
import com.novel.mapper.NovelChapterMapper;
import com.novel.mapper.NovelMapper;
import com.novel.mapper.UserMapper;
import com.novel.pojo.novel.Novel;
import com.novel.pojo.novel.NovelChapter;
import com.novel.pojo.system.ChapterOrder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateUtils;
import org.quartz.JobExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.entity.Example;

import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

/**
 * 根据购买记录，计算作家的稿酬收入并扣除抽成
 */
@Slf4j
@Component
public class ClearAuthorIncomeJob extends QuartzJobBean {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ChapterOrderMapper chapterOrderMapper;

    @Autowired
    private NovelChapterMapper novelChapterMapper;

    @Autowired
    private NovelMapper novelMapper;

    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext) {
        //查询前一天全部的章节购买记录
        Date beforeDay = DateUtils.addDays(new Date(), -1);
        Date begin = DateUtils.truncate(beforeDay, Calendar.DATE);
        Date end = DateUtils.addDays(beforeDay, Calendar.DATE);
        List<ChapterOrder> chapterOrderList = chapterOrderMapper.calculateChapterAndCost(begin, end);
        //建立章节id和购买章节的虚拟币的关系
        HashMap<String, Double> chapterIdAndCostMap = new HashMap<>(chapterOrderList.size());
        chapterOrderList.forEach(chapterOrder -> {
            //已经再这里扣除抽成
            chapterIdAndCostMap.put(chapterOrder.getChapterId(), chapterOrder.getCost() * 0.8d);
        });

        Example chapterExample = new Example(NovelChapter.class);
        chapterExample.selectProperties("chapterId", "novelId");
        chapterExample.createCriteria().andIn("chapterId", chapterIdAndCostMap.keySet());
        List<NovelChapter> novelChapterList = novelChapterMapper.selectByExample(chapterExample);
        //建立 章节id和小说id之间的关系
        ImmutableListMultimap<String, NovelChapter> novelIdAndChapterMap = Multimaps.index(novelChapterList, NovelChapter::getNovelId);

        Example novelExample = new Example(Novel.class);
        novelExample.selectProperties("authorId", "novelId");
        novelExample.createCriteria().andIn("novelId", novelIdAndChapterMap.keySet());
        List<Novel> novelList = novelMapper.selectByExample(novelExample);
        //建立 小说id和作者id之间的关系
        ImmutableListMultimap<String, Novel> authorIdAndNovelMap = Multimaps.index(novelList, Novel::getAuthorId);

        //计算每个作者该获得多少钱
        authorIdAndNovelMap.keySet().forEach(authorId -> {
            //获取小说id
            List<String> novelIds = authorIdAndNovelMap.get(authorId).stream().map(Novel::getNovelId).collect(Collectors.toList());
            //获取小说对应的章节id
            List<String> chapterIds = new ArrayList<>();
            novelIds.forEach(ids -> {
                chapterIds.addAll(novelIdAndChapterMap.get(ids).stream().map(NovelChapter::getChapterId).collect(Collectors.toList()));
            });
            //根据章节id计算应得钱
            AtomicReference<Double> amount = new AtomicReference<>(0.0);
            chapterIds.forEach(chapterId -> {
                amount.updateAndGet(v -> v + chapterIdAndCostMap.get(chapterId));
            });
            //把结果保存到数据库中
            userMapper.updatedAuthorIncomeByAuthorId(authorId, amount.get() * 0.8);
        });

    }
}